package com.lei.baselibrary.base.data.net

import com.lei.baselibrary.base.common.BaseConstant
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @ProjectName : MyMall
 * @Author : 雷金泷
 * @Time : 2021/2/24 19:27
 * @Description : 文件描述
 */
class RetrofitFactory private constructor() {
    companion object {
        val instance: RetrofitFactory by lazy { RetrofitFactory() }
    }

    private val interceptor: Interceptor = Interceptor { chain ->
        val request = chain.request()
            .newBuilder()
            .addHeader("Content_type", "Application/json")
            .addHeader("charset", "UTF-8")
            .addHeader("token", "")
            .build()
        chain.proceed(request)
    }
    private val retrofit: Retrofit = Retrofit.Builder()
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(BaseConstant.SERVICE_ADDRESS)
        .client(initClient())
        .build()

    //okhttp创建
    private fun initClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .addInterceptor(initLogInterceptor())
            .build()
    }

    private fun initLogInterceptor(): HttpLoggingInterceptor {
        return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
    }
    //具体服务实例化
    fun <T> create(service:Class<T>) : T{
        return retrofit.create(service)
    }
}